import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late final WebViewController controller;
  String valueStr = '';

  final String htmlStr = '''
  <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>我的网页qqq</title>
</head>
<body>
<h1>欢迎来到我的网页</h1>
<p>这是一个段落。</p>
<a href="https://www.baidu.com">点击这里访问我的主页</a>
<script>
    function methodName() {
        var randomNum = Math.floor(Math.random() * 101);
        const resizeObserver = new ResizeObserver(entries =>
          Report.postMessage(randomNum))
        resizeObserver.observe(document.body)
    }
    methodName();
</script>
</body>
</html>
  ''';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    //https://blog.51cto.com/u_16213619/10981309
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..addJavaScriptChannel("Report", onMessageReceived: (message) {
        print('从JavaScript接收到消息: ${message.message}');

        valueStr = message.message;
        setState(() {});
      })
      ..loadHtmlString(htmlStr);
    // ..loadRequest(Uri.parse('http://www.baidu.com'));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('加载本地HTML$valueStr'),
        ),
        body: Container(
          width: double.infinity,
          height: double.infinity,
          color: Colors.red,
          child: WebViewWidget(controller: controller),
        ),
        floatingActionButton: ElevatedButton(
          child: Text('刷新'),
          onPressed: () {
            //调用js，重新赋值valueStr
            controller.runJavaScript('methodName()');
          },
        ),
      ),
    );
  }
}
